package com.jinken.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jinken.common.result.BaseResult;
import com.jinken.common.service.IAccountService;
import com.jinken.entity.TAccount;
import com.jinken.mapper.AccountMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@DubboService
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Transactional
    public BaseResult debit(String userId, Integer money) {
        //设置条件
        LambdaQueryWrapper<TAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TAccount::getUserId, userId);

        TAccount account = accountMapper.selectOne(queryWrapper);

        if (Objects.isNull(account)) {
            return BaseResult.error("用户不存在");
        }

        if (account.getMoney() < money) {
            return BaseResult.error("余额不足");
        }

        //扣减余额
        account.setMoney(account.getMoney() - money);

        //修改数据库
        int row = accountMapper.updateById(account);
        if(row==1){
            return BaseResult.success();
        }

        return BaseResult.error("扣减余额失败，服务异常");
    }
}
